package com.demo.project_template.base.sms.impl;

import com.alibaba.fastjson2.JSON;
import com.demo.project_template.base.sms.SendSmsService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

/**
 * 腾讯云短信发送工具类
 * 该类使用是需要替换TODO中的参数
 */
@Data
@Service
@Slf4j
public class TencentSendSmsServiceImpl implements SendSmsService {

    /**
     * 发送短信secretId
     */
    public String secretId = "";
    /**
     * 发送短信secretKey
     */
    public String secretKey = "";
    /**
     * 发送短信应用id
     */
    public String sdkAppId = "";
    /**
     * 发送短信签名内容
     */
    public String signName = "";

    /**
     * 腾讯云发送验证码
     */
    @Override
    public void sendSms(String templateId, String tel, String[] templateParamSet) {
        try {
            SmsClient client = getSmsClient();
            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppid(sdkAppId);
            req.setSign(signName);
            req.setTemplateID(templateId);
            req.setTemplateParamSet(templateParamSet);
            String[] phoneNumberSet = {"86" + tel};
            req.setPhoneNumberSet(phoneNumberSet);

            SendSmsResponse res = client.SendSms(req);
            log.info("短信发送结果={}", JSON.toJSONString(res));
        } catch (TencentCloudSDKException e) {
            e.fillInStackTrace();
        }
    }

    @NotNull
    private SmsClient getSmsClient() {
        Credential cred = new Credential(secretId, secretKey);
        // 实例化一个http选项，可选，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setConnTimeout(60);
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod("HmacSHA256");
        clientProfile.setHttpProfile(httpProfile);
        return new SmsClient(cred, "ap-guangzhou", clientProfile);
    }
}
